package com.tarena.lbs.business.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.enums.AuditStatusEnum;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.pojo.BusinessDto;
import com.tarena.lbs.business.base.exception.BusinessServiceException;
import com.tarena.lbs.business.base.response.StatusCode;
import com.tarena.lbs.business.dao.mapper.BusinessMapper;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class BusinessRepositoryImpl implements BusinessRepository{
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private StoreMapper storeMapper;

    //新增商家
    @Override
    public void saveParam(BusinessPO businessPO) {
        BusinessPO po = new BusinessPO();
        po.setId(businessPO.getId());
        po.setBusinessName(businessPO.getBusinessName());
        po.setIndustryType(businessPO.getIndustryType());
        po.setBusinessHeadName(businessPO.getBusinessHeadName());
        po.setBusinessHeadPhone(businessPO.getBusinessHeadPhone());
        po.setCompanyAddress(businessPO.getCompanyAddress());
        po.setBusinessLicense(businessPO.getBusinessLicense());
        po.setBusinessIntroduction(businessPO.getBusinessIntroduction());
        po.setEntryTime(new Date());
        po.setAuditRemarks(businessPO.getAuditRemarks());
        po.setBusinessLogo(businessPO.getBusinessLogo());
        po.setBusinessStatus(2);
        businessMapper.insert(po);
    }

    @Override
    public BusinessPO findByBusinessName(String businessName) {
        log.debug("查询商家名称：{}",businessName);
        BusinessPO businessPO = businessMapper.selectOne(
                new QueryWrapper<BusinessPO>().eq("business_name", businessName)
        );
        log.debug("查询商家名称：{}，结果：{}", businessName, businessPO != null ? "存在" : "为空");
        return businessPO;
    }

    @Override
    public BusinessDto getBusinessById(Integer businessId) throws BusinessServiceException {
        try {
            // 从数据库查询商家信息
            BusinessPO businessPO = businessMapper.selectById(businessId);

            // 如果查询结果为空，返回null
            if (businessPO == null) {
                return null;
            }

            // 将 BusinessPO 转换为 BusinessDto
            BusinessDto businessDto = new BusinessDto();
            BeanUtils.copyProperties(businessPO, businessDto);

            return businessDto;
        } catch (Exception e) {
            log.error("查询商家信息失败，businessId: {}", businessId, e);
            throw new BusinessServiceException(StatusCode.QUERY_BUSINESS_FAILED);
        }
    }


    //查询商家列表
    @Override
    public PageResult<BusinessVO> getBusinessList(BusinessQuery query) {
        log.debug("查询商家列表，入参：{}",query);
        QueryWrapper<BusinessPO> wrapper = new QueryWrapper<>();
        if (query.getBusinessName() != null) {
            wrapper.like("business_name", query.getBusinessName());
        }
        if (query.getBusinessHeadPhone() != null) {
            wrapper.like("business_head_phone", query.getBusinessHeadPhone());
        }
        if (query.getBusinessStatus() != null) {
            wrapper.eq("business_status", query.getBusinessStatus());
        }
        if (query.getStartingTime() != null && query.getEndTime() != null) {
            wrapper.between("entry_time", query.getStartingTime(), query.getEndTime());
        }

        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<BusinessPO> businessPOS = businessMapper.selectList(wrapper);
        PageInfo<BusinessPO> pageInfo = new PageInfo<>(businessPOS);
        PageResult<BusinessVO> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setPageNo(pageInfo.getPageNum());
        // 使用流式转换并添加空值检查
        List<BusinessVO> businessVOList = Optional.ofNullable(businessPOS)
                .orElse(new ArrayList<>())
                .stream()
                .map(businessPO -> {
                    BusinessVO businessVO = new BusinessVO();
                    BeanUtils.copyProperties(businessPO, businessVO);
                    businessVO.setIndustryName(businessPO.getBusinessName());
                    return businessVO;
                })
                .collect(Collectors.toList());
        pageResult.setObjects(businessVOList);
        return pageResult;
    }
    //查询商家详情
    @Override
    public BusinessStoreVO selectBusinessStore(Integer businessId) throws BusinessServiceException {
        log.debug("查询商家详情:{}",businessId);

        // 查询商家信息
        BusinessPO businessPO = businessMapper.selectById(businessId);
        if (businessPO == null) {
            return null;
        }

        // 转换为 BusinessStoreVO
        BusinessStoreVO businessStoreVo = new BusinessStoreVO();
        BeanUtils.copyProperties(businessPO, businessStoreVo);

        try {
            // 查询店铺信息并设置到storeVoList
            QueryWrapper<StorePO> wrapper = new QueryWrapper<>();
            wrapper.eq("business_id", businessId);
            List<StorePO> storePOList = storeMapper.selectList(wrapper);
            //空值检查
            if (storePOList != null && !storePOList.isEmpty()) {
                // 转换为 StoreVO 列表
                List<StoreVO> storeVoList = storePOList.stream()
                        .map(storePO -> {
                            StoreVO storeVO = new StoreVO();
                            BeanUtils.copyProperties(storePO, storeVO);
                            return storeVO;
                        })
                        .collect(Collectors.toList());

                businessStoreVo.setStoreVOList(storeVoList);
                }
            } catch(Exception e){
                throw new BusinessServiceException(StatusCode.QUERY_STORE_FAILED);
            }


        return businessStoreVo;
    }

}
